#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Time: 2023/6/15 12:09
# @Author: Anthony (anthony66888@163.com)
# @description: 
"""
import datetime
import random
import time
import traceback
from urllib import parse
import requests
from auto_battle_room import init_login
from auto_battle_room.tf_big_battle_roll import add_big_battle_roll
from auto_battle_room.utils.yaml_control import YamlControl
from user_info import batch_add_balance


class AutoJoinBattle(object):
    def __init__(self):
        """
        获取玩家列表并登陆、箱子列表，可输入可固定
        """
        self.config_data = YamlControl("/data/config.yaml").read_yaml()  # 读取配置项
        self.host = self.config_data["host"]  # 获取环境域名
        self.yaml_control_user = YamlControl("/data/user_info.yaml")
        self.yaml_control_battle = YamlControl("/data/battle_room.yaml")

        init_room_list = {"room_list": self.get_current_room()}
        self.yaml_control_battle.write_yaml(init_room_list)

    def get_user_balance(self, user):
        """
        获取用户当前星币余额
        :return:
        """
        url = "/api/personalCenter/customerDetail"
        headers = {
            "Token": user["token"]
        }
        res = requests.get(self.host + url, headers)
        if res.json()["status"] == 0:
            return res.json()["data"]["balance"]
        elif res.json()["status"] == 401:
            init_login(account=user["account"])
        else:
            return 50

    def join_robot(self, battle_code, pos, user):
        """
        添加机器人
        :param battle_code: 对战房间ID
        :param token: 添加机器人的用户
        :return:
        """
        url = "/api/battle/joinBot"
        headers = {
            "Token": user["token"],
            "Content-Type": "application/x-www-form-urlencoded"
        }
        data = {
            "battleCode": battle_code,
            "pos": pos
        }
        data = parse.urlencode(data)
        # requests.post(url=self.host + url, data=data, headers=headers)
        try:
            response = requests.post(url=self.host + url, data=data, headers=headers)
            if response.json()["status"] == 1:  # "賬戶餘額不足,請先充值"
                # YamlControl("/data/user_info.yaml").del_user_yaml("user_info", "token", token)
                # self.yaml_control_user.del_user_yaml("user_info", "token", user["token"])
                batch_add_balance(phone1=user["account"], phone2=user["account"])
                time.sleep(1)
                return response.json()["status"]
            elif response.json()["status"] == 401:
                return response.json()["status"]
            else:
                time.sleep(random.randint(1, 3))  # 每次加入房间间隔时间
                return response.json()["status"]
            # res = response.text
            # return res
        except Exception as e:
            print(f"机器人参加对战报错：{e}")

    def join_battle(self, battle_code, pos, user):
        """
        真人参与对战
        :param battle_code: 对战房间ID
        :param pos: 对战位置
        :param user: 用户
        :return:
        """
        if self.get_user_balance(user) and self.get_user_balance(user) <= 10:  # "賬戶餘額不足,請先充值"
            return 400
        else:
            url = "/api/battle/joinBattle"
            headers = {
                "Token": user["token"],
                "Content-Type": "application/x-www-form-urlencoded"
            }
            data = {
                "battleCode": battle_code,
                "pos": pos
            }
            data = parse.urlencode(data)
            # requests.post(url=self.host + url, data=data, headers=headers)
            try:
                response = requests.post(url=self.host + url, data=data, headers=headers)

                # return response.json()["status"]
            except Exception as e:
                print(f"真人参加对战报错：{e}")
                return 403
            else:
                if response.json()["status"] == 1:  # or self.get_user_balance(user) <= 10:  # "賬戶餘額不足,請先充值"
                    # YamlControl("/data/user_info.yaml").del_user_yaml("user_info", "token", token)
                    # self.yaml_control_user.del_user_yaml("user_info", "token", token)
                    batch_add_balance(phone1=user["account"])
                    time.sleep(random.randint(2, 4))  # 每次加入房间间隔时间
                    return 400  # response.json()["status"]
                elif response.json()["status"] == 401:
                    return response.json()["status"]
                    # init_login(account=user["account"])
                elif response.json()["status"] == 0:
                    return response.json()["status"]
                else:
                    time.sleep(random.randint(2, 6))  # 每次加入房间间隔时间
                    return response.json()["status"]

    def room_detail(self, battle_code, user):
        # token = YamlControl("/data/user_info.yaml").read_yaml()["user_info"][0]["token"]
        # user = self.yaml_control_user.read_yaml()["user_info"][0]
        url = "/api/battle/getBattleDetail"
        data = {
            "battleCode": battle_code
        }
        headers = {
            "Token": user["token"]
        }
        try:
            res = requests.get(self.host + url, params=data, headers=headers)
            return res.json()
            # if res.json()["status"] == 401:
            #     init_login(account=user["account"])
            # else:
            #     return res.json()
        except Exception as e:
            print(f"获取对战房间详情报错：{e}")

    def random_join_battle(self, battle_code, user_list, room_info):
        """
        如果是房主添加一个机器人或两个机器人，非房主则真人参与对战
        @param user_list:  用户列表
        @param battle_code: 对战房间ID
        @param room_info: 房间详情
        """
        # room_info = self.room_detail(battle_code, user_list[0])["data"]
        room_owner = room_info["customerId"]  # 获取房主ID

        # 获取房间内未被占用的位置
        occupied_pos_list = [i["pos"] for i in room_info["customerList"]]
        pos_list = [i for i in range(1, room_info["countCustomer"]+1)
                    if str(i) not in occupied_pos_list]
        need_login_user = []
        need_delete_user = []
        # 参加对战
        try:
            if pos_list is not None and len(pos_list) > 0:
                for pos in pos_list:
                    user = random.choice(user_list)
                    if self.able_to_jon(battle_code, user):
                        if str(user["uid"]) == room_owner:
                            pass
                            # status = self.join_robot(battle_code, pos, user=user)
                            # time.sleep(1)
                            # if status == 401:
                            #     need_login_user.append(user)
                            # else:
                                # if self.able_to_jon(battle_code, user):
                                #     self.join_robot(battle_code, pos, user=user)
                        else:
                            status = self.join_battle(battle_code, pos, user=user)
                            if status == 401:
                                need_login_user.append(user)

                            elif status == 0:  # 大额房间，需要加入对应的roll房
                                if room_info["totalPrice"] and room_info["totalPrice"] >= 200:
                                    # 加入roll房
                                    try:
                                        add_big_battle_roll(user["uid"])
                                    except Exception as e:
                                        print(f"用户{user}加入roll房报错：{e}")
                            elif status == 400:
                                need_delete_user.append(user)
                            elif status == 403:
                                need_delete_user.append(user)
                        time.sleep(random.randint(4, 15))
            return need_login_user, need_delete_user
        except Exception as e:
            traceback.print_exc()
            print(f"随机参与对战报错：{e}")

    def get_current_room(self):
        url = "/api/battle/getList"
        data = {
            "page": 1,
            "pageSize": 16,
            "mode": -1,
            "state": 0
        }
        try:
            res = requests.get(self.host + url, data)
            if res.json()["status"] == 0:
                battle_info_list = res.json()["data"]["pageData"]
                battle_code_list = []
                if battle_info_list is not None and len(battle_info_list) > 0:

                    for battle_info in battle_info_list:
                        # 判断是否主播房间
                        if battle_info["hostType"] != "HOST":
                            # if room_info["customerList"][0]["customerId"] not in self.anchor_list["anchor_id_list"]:
                            if int(battle_info["countCustomer"]) != len(battle_info["customerList"]):
                                battle_code_list.append(battle_info["battleCode"])
                return battle_code_list
            else:
                print("获取当前房间要参与的对战失败: ", res.json()["msg"])
        except Exception as e:
            print(f"获取当前房间要参与的对战报错：{e}")
            traceback.print_exc()

    def able_to_jon(self, battle_code, user):
        flag = False
        res = self.room_detail(battle_code, user)

        room_state = res["data"]["state"]
        if res is not None and room_state == 0:
            flag = True
        return flag

    def room_to_join(self):
        """获取本轮要参与的房间：n s内没人参与的对战"""
        current_room = self.get_current_room()
        try:
            old_room = self.yaml_control_battle.read_yaml()["room_list"]
            if old_room is None or len(old_room) == 0:
                return current_room
            else:
                join_rooms = list(set(current_room) & set(old_room))  # 本轮要参与的房间
                return join_rooms
        except Exception as e:
            print(f"获取本轮要参与的对战报错：{e}")
            traceback.print_exc()
            return []


def auto_join():
    join = AutoJoinBattle()
    join_wait_time = join.config_data["join_wait_time"]
    user_list = join.yaml_control_user.read_yaml()["user_info"]
    i = 0
    while True:
        now_time = datetime.datetime.now().strftime("%H:%M")
        if "00:30" <= now_time <= "01:30":
            break
        if len(user_list) == 0:
            now_times = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            print(f"{now_times}用户的钱都花完了, 一共参与对战共{i}轮")
            break
        try:
            room_list = join.room_to_join()
            if room_list is None or len(room_list) == 0:
                print(f"{now_time}  本轮没有要参与的对战房")
            else:
                for room in room_list:
                    res = join.room_detail(room, user_list[0])
                    if res["status"] == 401:
                        token = init_login(account=user_list[0]["account"])
                        [d.update({"token": token}) for d in user_list if d["uid"] == user_list[0]["uid"]]

                    if res["data"]["totalPrice"] and res["data"]["totalPrice"] <= 500:
                        # user = random.choice(user_list)
                        need_login_user, need_delete_user = join.random_join_battle(room, user_list, res["data"])
                        if need_login_user and len(need_login_user) > 0:
                            for user in need_login_user:
                                token = init_login(account=user["account"])
                                [d.update({"token": token}) for d in user_list if d["uid"] == user["uid"]]
                        # 如果用户没钱了，救下机不玩了
                        # if need_delete_user and len(need_delete_user) > 0:
                        #     for user in need_delete_user:
                        #         user_list.remove(user)
                        time.sleep(1)
                    # elif res["data"]["totalPrice"] and res["data"]["totalPrice"] > 500 and random.randint(1,5):

                i += 1
                now_times = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                print(f"{now_times}  第{i}轮参加对战房成功")
            join.yaml_control_battle.write_yaml({"room_list": join.get_current_room()})  # 复写待加入的room_list
        except Exception as e:
            print(f"自动参加房间报错：{e}")
            traceback.print_exc()
            # init_login()
            time.sleep(5)
            continue

        time.sleep(join_wait_time)  # n秒后打掉无人参与的房间


if __name__ == '__main__':
    auto_join()
    # a = []
    # b = [1, 2, 3]
    # print(list(set(a) & set(b)))
